const { app, BrowserWindow, ipcMain, Tray, Menu } = require('electron')
const path = require('path')
const axios = require('axios')
const iconv = require('iconv-lite')
const fs = require('fs')
const log = require('electron-log')

// 添加 isDev 的定义
const isDev = process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true'

// 配置日志
log.transports.file.level = 'info'
log.transports.file.maxSize = 1024 * 1024 * 10 // 10MB
log.transports.file.format = '[{y}-{m}-{d} {h}:{i}:{s}] [{level}] {text}'
// 设置日志文件路径
log.transports.file.resolvePathFn = () => path.join(app.getPath('userData'), 'logs/main.log')

// 记录启动时间
log.info('应用启动时间:', new Date().toLocaleString())
log.info('当前环境:', isDev ? 'development' : 'production')

// 记录系统信息
log.info('系统信息:', {
  platform: process.platform,
  arch: process.arch,
  nodeVersion: process.version,
  electronVersion: process.versions.electron,
  appVersion: app.getVersion()
})

let mainWindow
let tray = null

function createTray() {
  const { nativeImage } = require('electron')
  
  // 创建���个 16x16 的图标
  const image = nativeImage.createFromDataURL(`
    
  `)
  
  // 设置合适的图标大小
  const trayIcon = image.resize({
    width: 16,
    height: 16
  })
  
  // 创建托盘
  tray = new Tray(trayIcon)
  
  // 创建托盘菜单
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示主窗口',
      click: () => {
        if (mainWindow) {
          mainWindow.show()
          mainWindow.focus()
        }
      }
    },
    { type: 'separator' },
    {
      label: '退出',
      click: () => {
        app.isQuiting = true
        app.quit()
      }
    }
  ])
  
  tray.setToolTip('股票行情')
  tray.setContextMenu(contextMenu)
  
  // 双击托盘图标显示窗口
  tray.on('double-click', () => {
    if (mainWindow) {
      mainWindow.show()
      mainWindow.focus()
    }
  })
  
  log.info('托盘创建成功')
}

function createWindow() {
  const win = new BrowserWindow({
    width: 600,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: true
    }
  })

  // 创建菜单模板
  const template = [
    {
      label: '文件',
      submenu: [
        {
          label: '退出',
          role: 'quit'
        }
      ]
    },
    {
      label: '设置',
      click: () => {
        // 打开设置窗口
        const settingsWindow = new BrowserWindow({
          width: 400,
          height: 300,
          parent: win,
          modal: true,
          autoHideMenuBar: true, // 隐藏菜单栏但保留标题栏
          minimizable: false, // 禁用最小化按钮
          maximizable: false, // 禁用最大化按钮
          webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
          }
        })
        settingsWindow.loadFile('src/renderer/settings.html')
      }
    },
    {
      label: '关于',
      click: () => {
        // 打开关于对话框
        const aboutWindow = new BrowserWindow({
          width: 400,
          height: 300,
          parent: win,
          modal: true,
          autoHideMenuBar: true, // 隐藏菜单栏但保留标题栏
          minimizable: false, // 禁用最小化按钮
          maximizable: false, // 禁用最大化按钮
          resizable: false,
          webPreferences: {
            nodeIntegration: true,
            contextIsolation: false
          }
        })
        aboutWindow.loadFile('src/renderer/about.html')
      }
    }
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)

  // 根据环境加载不同的页面
  if (process.env.NODE_ENV === 'development') {
    win.loadURL('http://localhost:5173')
  } else {
    win.loadFile('./dist/index.html')
  }
}

// 搜索股票
ipcMain.handle('search-stocks', async (event, keyword) => {
  try {
    const url = `https://proxy.finance.qq.com/cgi/cgi-bin/smartbox/search?stockFlag=1&fundFlag=1&app=official_website&query=${encodeURIComponent(keyword)}`
 
    const response = await axios.get(url, {
      headers: {
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.9', 
        'Connection': 'keep-alive',
        'Origin': 'https://stockapp.finance.qq.com',
        'Referer': 'https://stockapp.finance.qq.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
        'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"'
      }
    })
    
    return {
      data: response.data
    }
  } catch (error) {
    log.error('搜索股票失败:', { keyword, error: error.message, stack: error.stack })
    return { error: error.message }
  }
})

// 获取股票行情数据
ipcMain.handle('fetch-stock-quotes', async (event, codes) => {
  try {
    // 将所有代码用逗号连接成一个字符串
    const codesStr = codes.join(',')
    const url = `http://qt.gtimg.cn/q=${codesStr}`
    //log.info('获取股票行情URL:', url)
    const response = await axios.get(url, {
      responseType: 'arraybuffer', 
      headers: {
        'Accept-Charset': 'GBK,utf-8;q=0.7,*;q=0.3'
      }
    })

    // 解码响应数据
    const text = iconv.decode(response.data, 'gbk')
    
    // 按换行符分割成多个报价
    const quotes = text.split('\n').filter(quote => quote.trim())
    //log.info('获取股票行情成功:', { quotes })
    return quotes
  } catch (error) {
    log.error('获取股票行情失败:', { codes, error: error.message, stack: error.stack })
    return null
  }
})

// 本地存储相关
function getStorageFilePath() {
  const filePath = path.join(app.getPath('userData'), 'stocks.json')
  log.debug('获取存储文件路径:', filePath)
  return filePath
}

ipcMain.handle('load-stored-stocks', async () => {
  try {
    const filePath = getStorageFilePath()
    if (fs.existsSync(filePath)) {
      const data = fs.readFileSync(filePath, 'utf8')
      const stocks = JSON.parse(data)
      log.info('加载本地存储成功:', { stockCount: stocks.length })
      return stocks
    }
    log.info('本地存储文件不存在，返回空数组')
    return []
  } catch (error) {
    log.error('读取本地存储失败:', { error: error.message, stack: error.stack })
    return []
  }
})

ipcMain.handle('save-stocks', async (event, stocks) => {
  try {
    const filePath = getStorageFilePath()
    fs.writeFileSync(filePath, JSON.stringify(stocks, null, 2), 'utf8')
    log.info('保存到本地存储成功:', { stockCount: stocks.length })
    return true
  } catch (error) {
    log.error('保存到本地存储失败:', { error: error.message, stack: error.stack })
    return false
  }
})

// 修改应用初始化顺序
app.whenReady().then(() => {
  // 先创建托盘，再创建窗口
  createTray()
  createWindow()
  log.info('应用初始化完成')

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
      log.info('通过 activate 事件创建窗口')
    }
  })
})

// 确保应用退出时清理托盘
app.on('before-quit', () => {
  app.isQuiting = true
  if (tray) {
    tray.destroy()
  }
  log.info('应用准备退出')
})

app.on('window-all-closed', () => {
  log.info('所有窗口已关闭')
  if (process.platform !== 'darwin') {
    log.info('应用退出')
    app.quit()
  }
})

// 捕获未处理的异常
process.on('uncaughtException', (error) => {
  log.error('未捕获的异常:', { error: error.message, stack: error.stack })
})

process.on('unhandledRejection', (reason, promise) => {
  log.error('未处理的 Promise 拒绝:', { reason, promise })
})